package com.yztc.xiami_app.utils;

import android.content.Context;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by bodhixu on 2016/10/8.
 */
public class MyUtils {

    /**
     * 将assets下的省市区3级联动的数据库文件资源复制到应用程序的databases目录下
     * @param context
     * @param fileName
     */
    public static void copyAssetsToDB(Context context, String fileName) throws IOException{

        File file = new File("/data/data/" + context.getPackageName()
                + "/databases/" + fileName);
        if (file.exists()) {
            return;
        }

        //打开assest文件，获得输入流
        InputStream is = context.getAssets().open(fileName);
        BufferedInputStream bis = new BufferedInputStream(is);

        //获得写入文件的输出流
        FileOutputStream fos = new FileOutputStream("/data/data/" + context.getPackageName()
                + "/databases/" + fileName);
        BufferedOutputStream bos = new BufferedOutputStream(fos);

        byte[] data = new byte[1024];
        int len;
        while ((len = bis.read(data)) != -1){
            bos.write(data, 0, len);
        }

        bis.close();
        bos.close();
    }
}
